mod handlers;

use axum::{
    routing::{get, post, delete}, Router,
};

// 处理函数
async fn root() -> &'static str {
    "hello world!"
}

use tower_http::cors::{Any, CorsLayer};

#[tokio::main]
async fn main() {
    // tracing
    tracing_subscriber::fmt::init();

    // add cors
    let cors = CorsLayer::new()
        .allow_origin(Any);

    // add postgres
    dotenv::dotenv().ok();
    let db_url = std::env::var("DATABASE_URL")
        .expect("DATABASE URL not set");
    let pool = sqlx::PgPool::connect(&db_url)
        .await
        .expect("Error with pool connection");

    // add postgres table
    // sqlx::query(
    //     r#"
    //     CREATE TABLE IF NOT EXISTS products (
    //         id serial,
    //         name text,
    //         price integer
    //     );
    //     "#
    // )
    //     .execute(&pool)
    //     .await.expect("create table error!");

    let app = Router::new()
        .route("/", get(root))
        .route("/api/products", post(handlers::create_product))
        .route("/api/products", get(handlers::get_products))
        .route("/api/products/:id", get(handlers::get_one_product))
        .route("/api/products/:id", delete(handlers::del_one_product))
        .with_state(pool)
        .layer(cors);

    tracing::debug!("listening on port {}","0.0.0.0:3001");
    println!("listening on port {}", "0.0.0.0:3001");

    axum::Server::bind(&"0.0.0.0:3001".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}
